package com.storm.config.exception

import com.storm.common.exception.NonExistentException
import com.storm.common.exception.StatusInfo
import com.storm.common.exception.StormException
import com.storm.common.response.JSONResponse
import com.storm.common.response.fail
import com.storm.util.log
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.ResponseStatus

/**
 * 统一异常处理 现在只做封装
 * 后续可以记入到表
 */
class GlobalExceptionHandler {

    /**
     * 业务异常拦截
     */
    @ExceptionHandler(StormException::class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    fun businessException(e: StormException): JSONResponse<Any> {
        log.error("业务异常：${e.message}", e)
        return fail(status = e.status, result = e.data, msg = e.message)
    }

    /**
     * 业务异常拦截
     */
    @ExceptionHandler(NonExistentException::class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    fun nonExistentException(e: NonExistentException): JSONResponse<Void> {
        log.error("业务异常：{}", e.message, e)
        return fail(status = StatusInfo.NON_EXISTENT.status(),  msg = e.message)
    }


    /**
     * 运行异常拦截
     */
    @ExceptionHandler(RuntimeException::class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    fun runtimeException(e: java.lang.RuntimeException): JSONResponse<Void> {
        log.error("运行时异常：${e.message}", e)
        return fail(msg = e.message)
    }

}